import { makeAutoObservable } from 'mobx'
import { http } from '@/utils'
import type { TokenInfo, LoginForm, ApiRes, User, UserProfile } from '@/type'
import { getToken, setToken, removeToken } from '@/utils/token'

class UserStore {
  // 类型定义
  tokenInfo: TokenInfo
  userInfo: User
  userProfile: UserProfile
  constructor() {
    // 响应式处理
    makeAutoObservable(this)
    // 按照类型做数据初始化
    this.tokenInfo = getToken() || {
      token: '',
      refresh_token: '',
    }
    this.userInfo = {} as User
    this.userProfile = {} as UserProfile
  }
  login = async ({ mobile, code }: LoginForm) => {
    // 发送请求
    // 把数据拿到交给token
    // http.post函数是一个泛型函数 可以传入一个类型注解
    // 目的是注解一下将来返回值 res.data的类型
    // 方便我们获取各种参数
    const res = await http.post<ApiRes<TokenInfo>>('/authorizations', {
      mobile,
      code,
    })
    this.tokenInfo = res.data.data
    // 往本地存一份
    setToken(res.data.data)
  }
  // 获取用户中心
  getUser = async () => {
    const res = await http.get<ApiRes<User>>('/user')
    this.userInfo = res.data.data
  }
  // 获取个人信息
  getUserProfile = async () => {
    const res = await http.get<ApiRes<UserProfile>>('/user/profile')
    this.userProfile = res.data.data
  }
  // 更新个人信息
  updateUserProfile = async (value: string) => {
    // 更新接口
    await http.patch('/user/profile', {
      name: value,
    })
    // 更新数据
    this.getUserProfile()
  }
  // 清空个人信息
  removeUser = () => {
    this.tokenInfo = {} as TokenInfo
    this.userInfo = {} as User
    this.userProfile = {} as UserProfile
    removeToken()
  }
}

export default UserStore
